import marked from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/xcode.css'

export const EDITOR = {
    HEADER: 1,
    BOLD: 2,
    ITALIC: 3,
    LIST_OL: 4,
    LIST_UL: 5,
    CODE: 6,
    QUOTE: 7,
    IMG: 8
}

marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    tables: true,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: true,
    smartypants: false,
    highlight: (code) => {
        return hljs.highlightAuto(code).value;
    }
});

export function formatContent(comp, type, url) {
    let t = comp,
        start = t.selectionStart,
        end = t.selectionEnd,
        value = t.value,
        newValue = '';

    switch (type) {
        case EDITOR.HEADER:
            newValue = `${value.substring(0, start)}# ${value.substring(start, value.length)} `;
            break;
        case EDITOR.LIST_OL:
            newValue = `${value.substring(0, start)}1. ${value.substring(start, value.length)}`;
            break;
        case EDITOR.LIST_UL:
            newValue = `${value.substring(0, start)}* ${value.substring(start, value.length)}`;
            break;
        case EDITOR.BOLD:
            newValue = `${value.substring(0, start)}**${value.substring(start, end)}**${value.substring(end, value.length)}`;
            break;
        case EDITOR.ITALIC:
            newValue = `${value.substring(0, start)}*${value.substring(start, end)}*${value.substring(end, value.length)}`;
            break;
        case EDITOR.CODE:
            newValue = `${value.substring(0, start)}
\`\`\`
${value.substring(start, end)}
\`\`\`
${value.substring(end, value.length)}`;
            break;
        case EDITOR.QUOTE:
            newValue = `${value.substring(0, start)}> ${value.substring(start, value.length)}`;
            break;
        case EDITOR.IMG:
            newValue = `${value.substring(0, start)}![](${url}) ${value.substring(start, value.length)}`;
            break;
    }
    // console.log(newValue);

    return newValue;
}

/**
 * md 转换为 html
 * @param  {String} content md内容
 * @return {String}
 */
export default function md2html(content) {
    if (!content)
        return '';
    return marked(content);
}
